//
//  AliPayModel.m
//  SoundPill
//
//  Created by 宋旭东 on 15/12/29.
//  Copyright © 2015年 宋旭东. All rights reserved.
//

#import "AliPayModel.h"
#import "AFNetworking.h"
#import "JCAlertView.h"
#define Ali_parter @"2088021693271810"
#define Ali_seller @"soundpill@pillele.cn"
#define Ali_privateKey @"MIICXQIBAAKBgQDhPOwXc4nU8H+UmePyfOFn9QraMnGHuRqiUOyILWL/iQTmzv9tgdKBKo1UbjPlbmE8ZH4k9N7fmUmVyrttWwOwY2rXEfN4OunWHRKJlw6bZnqazdwuvSn4TR8Pc0uO0trxRjcummduA5Ye+bsPbluTaiO+hOg0TuhnUOzeX1ihewIDAQABAoGADU3K6Cuz5Xb7Iizg0O7dZYWMyYyXNhwR3aqH/hcoNM3EE1oArlgvtd9sj6Mev5uAdM++v7ITBAQK26Uo4vGwSvuBGxyVdB+BrXEC0xO4tx1KGjHxVUfZejEoMubL8PJ5aOehVSmCQWLCB3HrbQtOC3jiEO0YUHmjOQOCVl+ubvkCQQD5bm5C81Fkw1WCWsktcIgf9+YjLTag67eizNoCU55RDOQDy8FopXs2LQDLV32h3Cs0E4qi1NT7FiShJWsQ1fktAkEA5ytjmsjRZUZhva8289lGZVBpq09Tj1SJXpLAHz0hncFlNqHeF/AuptPoruS6r8pIvJufiWAuU4K5zzwuucpeRwJBAJLp+WXTvOg1qULbSE1MT9FMiS/E7L1BuWrZb7sZF1Gz3wVhWOzTM0xIm4QpZyUT8hp9PBYGd9/gPfjweixza40CQQDEga+z/g1yB7hCZFVUSFh8+zQ4OcCQUI5NZHYImBChZ6rAHC0NMFCX4/8h3LGNiWj3W1rsjmQS/UcyELivmoU1AkBWptb4rDZVhmrA0ifXwHwXfTvY8XNEnFHEtYraLiAwWONYhRuVqL17ouXaRzXwt8aLiJ18vHFe6XuSQ8nSglmT"

@interface AliPayModel ()
@property (strong, nonatomic) Product *product;
@property (strong, nonatomic) Order *order;
@end

@implementation AliPayModel
- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}
- (NSString *)generateTradeNO
{
    static int kNumber = 15;
    
    NSString *sourceStr = @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    NSMutableString *resultStr = [[NSMutableString alloc] init];
    srand(time(0));
    for (int i = 0; i < kNumber; i++)
    {
        unsigned index = rand() % [sourceStr length];
        NSString *oneStr = [sourceStr substringWithRange:NSMakeRange(index, 1)];
        [resultStr appendString:oneStr];
    }
    return resultStr;
}
- (void)pay:(NSString *)title price:(NSString *)price body:(NSString *)body work_id:(NSString *)work_id telNumber:(NSString *)number
{
    Order *order = [[Order alloc] init];
    order.partner = Ali_parter;
    order.seller = Ali_seller;
    order.tradeNO = [self generateTradeNO]; //订单ID（由商家自行制定）
    order.productName = title; //商品标题
    order.productDescription = body; //商品描述
    order.amount = [NSString stringWithFormat:@"%.2f",price.floatValue]; //商品价格
    order.rebate = @"0.0";
    order.notifyURL =  @"http://www.xxx.com"; //回调URL
    order.service = @"mobile.securitypay.pay";
    order.paymentType = @"1";
    order.inputCharset = @"utf-8";
    order.itBPay = @"30m";
    order.showUrl = @"m.alipay.com";
    
    //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
    NSString *appScheme = @"Soundlab";
    
    //将商品信息拼接成字符串
    NSString *orderSpec = [order description];
//    NSLog(@"orderSpec = %@",orderSpec);
    
    //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
    id<DataSigner> signer = CreateRSADataSigner(Ali_privateKey);
    NSString *signedString = [signer signString:orderSpec];
    
    //将签名成功字符串格式化为订单字符串,请严格按照该格式
    NSString *orderString = nil;
    if (signedString != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
//            NSLog(@"reslut = %@",resultDic);
            if ([[resultDic valueForKey:@"resultStatus"] intValue] == 9000) {
               NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:order.tradeNO,@"orderNO",
                                    [NSNumber numberWithFloat:order.amount.floatValue],@"price",
                                    [NSNumber numberWithInt:1],@"amount",
                                    [NSNumber numberWithFloat:order.rebate.floatValue],@"rebate",
                                    [NSNumber numberWithFloat:(order.amount.floatValue - order.rebate.floatValue)],@"outlay",
                                    [NSNumber numberWithInt:1],@"orderType",
                                    [NSNumber numberWithInt:1],@"orderFunc",
                                    [NSNumber numberWithBool:YES],@"orderStatus",
                                    work_id,@"work_id",
                                    order.productName,@"title",
                                    order.productDescription,@"detail",
                                    number,@"phoneNum",
                                    nil];
                [self postPayInfo:dic status:[[resultDic valueForKey:@"resultStatus"] intValue]];
            } else {
                NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:order.tradeNO,@"orderNO",
                                     [NSNumber numberWithFloat:order.amount.floatValue],@"price",
                                     [NSNumber numberWithInt:1],@"amount",
                                     [NSNumber numberWithFloat:order.rebate.floatValue],@"rebate",
                                     [NSNumber numberWithFloat:(order.amount.floatValue - order.rebate.floatValue)],@"outlay",
                                     [NSNumber numberWithInt:1],@"orderType",
                                     [NSNumber numberWithInt:1],@"orderFunc",
                                     [NSNumber numberWithBool:NO],@"orderStatus",
                                     work_id,@"work_id",
                                     order.productName,@"title",
                                     order.productDescription,@"detail",
                                     number,@"phoneNum", nil];
                [self postPayInfo:dic status:[[resultDic valueForKey:@"resultStatus"] intValue]];
            }
        }];
    }
}
- (void)pay:(NSString *)title price:(NSString *)price goods:(NSString *)goods body:(NSString *)body work_id:(NSString *)work_id address:(NSString *)address
{
    Order *order = [[Order alloc] init];
    order.partner = Ali_parter;
    order.seller = Ali_seller;
    order.tradeNO = [self generateTradeNO]; //订单ID（由商家自行制定）
    order.productName = title; //商品标题
    order.productDescription = body; //商品描述
    order.amount = [NSString stringWithFormat:@"%.2f",price.floatValue]; //商品价格
    order.rebate = @"0.0";
    order.notifyURL =  @"http://www.xxx.com"; //回调URL
    order.service = @"mobile.securitypay.pay";
    order.paymentType = @"1";
    order.inputCharset = @"utf-8";
    order.itBPay = @"30m";
    order.showUrl = @"m.alipay.com";
    
    //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
    NSString *appScheme = @"Soundlab";
    
    //将商品信息拼接成字符串
    NSString *orderSpec = [order description];
    //    NSLog(@"orderSpec = %@",orderSpec);
    
    //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
    id<DataSigner> signer = CreateRSADataSigner(Ali_privateKey);
    NSString *signedString = [signer signString:orderSpec];
    
    //将签名成功字符串格式化为订单字符串,请严格按照该格式
    NSString *orderString = nil;
    if (signedString != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            //            NSLog(@"reslut = %@",resultDic);
            if ([[resultDic valueForKey:@"resultStatus"] intValue] == 9000) {
                NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:order.tradeNO,@"orderNO",goods,@"goods",
                                     [NSNumber numberWithFloat:order.amount.floatValue],@"price",
                                     [NSNumber numberWithInt:1],@"amount",
                                     [NSNumber numberWithFloat:order.rebate.floatValue],@"rebate",
                                     [NSNumber numberWithFloat:(order.amount.floatValue - order.rebate.floatValue)],@"outlay",
                                     [NSNumber numberWithInt:1],@"orderType",
                                     [NSNumber numberWithInt:1],@"orderFunc",
                                     [NSNumber numberWithBool:YES],@"orderStatus",
                                     work_id,@"work_id",
                                     order.productName,@"title",
                                     order.productDescription,@"detail",
                                     address,@"cont",
                                     nil];
                [self postTotalPayInfo:dic status:[[resultDic valueForKey:@"resultStatus"] intValue]];
            } else {
                NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:order.tradeNO,@"orderNO",goods,@"goods",
                                     [NSNumber numberWithFloat:order.amount.floatValue],@"price",
                                     [NSNumber numberWithInt:1],@"amount",
                                     [NSNumber numberWithFloat:order.rebate.floatValue],@"rebate",
                                     [NSNumber numberWithFloat:(order.amount.floatValue - order.rebate.floatValue)],@"outlay",
                                     [NSNumber numberWithInt:1],@"orderType",
                                     [NSNumber numberWithInt:1],@"orderFunc",
                                     [NSNumber numberWithBool:NO],@"orderStatus",
                                     work_id,@"work_id",
                                     order.productName,@"title",
                                     order.productDescription,@"detail",
                                     address,@"cont", nil];
                [self postTotalPayInfo:dic status:[[resultDic valueForKey:@"resultStatus"] intValue]];
            }
        }];
    }
}
- (void)postPayInfo:(NSDictionary *)dic status:(int)status
{
    NSString *url = @"http://123.57.1.143/api/order/create";
    NSString *requestheader = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
     AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:requestheader forHTTPHeaderField:@"authorization"];
    [manager POST:url parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (status == 9000) {
            if ([[responseObject valueForKey:@"compaign"] intValue] == 0) {
                [JCAlertView showOneButtonWithTitle:@"提示" Message:@"打赏成功，并通知作者" ButtonType: JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:^{
                    
                }];
            } else {
                [JCAlertView showOneButtonWithTitle:@"提示" Message:@"支付已成功，请留意短信" ButtonType: JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:^{
                    
                }];
            }
        } else {
            [JCAlertView showOneButtonWithTitle:@"提示" Message:@"支付未成功" ButtonType: JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:^{
                
            }];
            
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (void)postTotalPayInfo:(NSDictionary *)dic status:(int)status
{
    NSString *url = @"http://123.57.1.143/api/goods/create";
    NSString *requestheader = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:requestheader forHTTPHeaderField:@"authorization"];
    [manager POST:url parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (status == 9000) {
            if ([[responseObject valueForKey:@"compaign"] intValue] == 0) {
                [JCAlertView showOneButtonWithTitle:@"提示" Message:@"打赏成功，并通知作者" ButtonType: JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:^{
                    
                }];
            } else {
                [JCAlertView showOneButtonWithTitle:@"提示" Message:@"支付已成功，请留意短信" ButtonType: JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:^{
                    
                }];
            }
        } else {
            [JCAlertView showOneButtonWithTitle:@"提示" Message:@"支付未成功" ButtonType: JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:^{
                
            }];
            
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
@end
